<script>
import {ref, computed} from 'vue';
import ChatBox from "@/components/chatBox/index.vue";
import {ElMessage} from 'element-plus';
import {Chat, deleteChatSession, getHistory, startChat} from "@/api/api.js";
import {TokenService} from "@/stores/userStore.js";

export default {
  name: "QuestionAnswer",
  setup() {
    const chatHistory = ref([
      {
        id: 1,
        history: "历史记录",
        time: "12-31 10:20",
        isSelected: true,
        messages: [{text: `Q: 你好，你122131`, type: 'question'}, {text: "A:我不上谢谢", type: 'answer'}]
      },
    ]);
    const currentChatMessages = ref([]);
    const currentChatId = ref(1)
    const searchQuery = ref('');
    const transformMessages = (sourceMessages) => {
      let resultMessages = [];
      sourceMessages.map(message => {
        const question = {
          text: `Q: ${message.question}`,
          type: 'question'
        };
        const answer = {
          text: `A: ${message.answer}`,
          type: 'answer'
        };
        resultMessages.push(question)
        resultMessages.push(answer)
      });
      return resultMessages;
    }
    const transformChatSessions = (chatSessions) => {
      return chatSessions.map(session => ({
        id: session.id,
        history: session.chat_title,
        time: new Date(session.created_at).toLocaleTimeString('zh-CN', {hour: '2-digit', minute: '2-digit'}),
        isSelected: false,
        messages: transformMessages(session.messages)
      }));
    }
    const selectItem = (item) => {
      chatHistory.value.forEach(chatItem => {
        chatItem.isSelected = false;
      });
      item.isSelected = true;
      currentChatMessages.value = item.messages;
      currentChatId.value = item.id
    };
    const user_id =TokenService.getCurrentUserId()
    getHistory(user_id).then(res => {
      if (!res.success) {
       console.log(res)
      } else {
        console.log(res.message)
        chatHistory.value = transformChatSessions(res.chat_sessions)
        if (chatHistory.value.length > 0) {
          selectItem(chatHistory.value[0])
        }
      }
    }).catch(err => {
      console.log(err)
    })
    const addNewChat = () => {
      const user_id =TokenService.getCurrentUserId()
      startChat(user_id).then(res => {
        if (!res.success) {
         console.log(res)
        } else {
          currentChatId.value = res.chat_id
          const newChat = {
            id: currentChatId.value,
            history: "新对话",
            time: new Date().toLocaleTimeString('zh-CN', {hour: '2-digit', minute: '2-digit'}),
            isSelected: true,
            messages: []
          };
          chatHistory.value.push(newChat);
          selectItem(newChat);
        }
      }).catch(err => {
        console.log(err)
      })
    };
    selectItem(chatHistory.value[0])
    const DeleteChat = () => {
      currentChatMessages.value = []
      deleteChatSession(currentChatId.value).then(res => {
        if (!res.success) {
         console.log(res)
        } else {
          console.log(res.message)
          chatHistory.value = chatHistory.value.filter(chat => chat.id !== currentChatId.value)
          selectItem(chatHistory.value[0])
        }
      })

    };
    const filteredChatHistory = computed(() => {
      if (!searchQuery.value) {
        return chatHistory.value;
      }
      return chatHistory.value.filter(chat =>
        chat.history.toLowerCase().includes(searchQuery.value.toLowerCase())
      );
    });
    const exportChatRecord = () => {
      try {
        // 检查 currentChatMessages.value 是否为空
        if (!currentChatMessages.value || currentChatMessages.value.length === 0) {
          console.log('没有可导出的聊天记录');
          return;
        }

        // 将当前聊天记录转换为 JSON 字符串
        const blob = new Blob([JSON.stringify(currentChatMessages.value, null, 2)], {type: 'application/json'});
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = 'chat_record.json';
        link.click();
        URL.revokeObjectURL(url);

        // 提示用户导出成功
        console.log('导出成功');
      } catch (error) {
        // 捕获并处理可能的错误
        console.error('导出聊天记录时发生错误:', error);
        console.log('导出失败');
      }
    };
    return {
      chatHistory,
      searchQuery,
      selectItem,
      addNewChat,
      DeleteChat,
      filteredChatHistory,
      currentChatMessages,
      exportChatRecord,
      currentChatId
    };
  },
  components: {
    ChatBox
  },
};
</script>

<template>
  <main class="question-answer">
    <div class="left">
      <div class="header">
        <div class="content">
          <el-icon>
            <DocumentCopy/>
          </el-icon>
          <i>{{ $t('qa.chatHistory') }}</i>
        </div>
        <input type="text" v-model="searchQuery" :placeholder="$t('qa.searchPlaceholder')" class="search-input">
        <button class="new-chat" @click="addNewChat">{{ $t('qa.newChat') }}</button>
      </div>
      <ul class="chat-list">
        <li class="chat-item"
            v-for="chat in filteredChatHistory"
            :key="chat.id"
            :class="{ selected: chat.isSelected }"
            @click="selectItem(chat)">
          <span>{{ chat.history }}</span>
          <span class="timestamp">{{ chat.time }}</span>
        </li>
      </ul>
    </div>

    <div class="right">
      <ChatBox :initialMessages="currentChatMessages" :delete-chat="DeleteChat" :exportChatRecord="exportChatRecord"
               :currentChatId="currentChatId"></ChatBox>
    </div>
  </main>
</template>

<style scoped>
@import "/src/css/base.css";
@import "/src/css/question-answer/index.css";
</style>
